package com.dqp.cslggroup.School;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.widget.Toolbar;
import androidx.preference.PreferenceManager;
import com.alibaba.fastjson.JSONObject;
import com.dqp.cslggroup.Api.schoolApi;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.SmartTableInfo.dakaInfo;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.twoTextViewAdapter;
import com.dqp.cslggroup.Util.*;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.dqp.cslggroup.UI.MyApplication.getContext;


public class login_daka extends BaseActivity {
    private String stuNum;
    private EditText sno;
    private Button cx;
    private ListView listView;
    private boolean select = true;
    private ViewStub viewstub_loading;
    ExecutorService threadPool = Executors.newFixedThreadPool(2);

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inquire_daka);
        EventBus.getDefault().register(this);
        Toolbar toolbar = findViewById(R.id.include_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        initDakaComp();
        if (NetCheckUtil.checkNet(login_daka.this)) {
            setUsetId();
            getDKdata();
        } else ToastUtil.showToast("请连接网络！");
    }


    private void initDakaComp() {
        sno = findViewById(R.id.daka_sno);
        cx = findViewById(R.id.cx_daka_button);
        listView = findViewById(R.id.daka_list);
        viewstub_loading = findViewById(R.id.viewstub_loading);
    }

    public void setUsetId() {
        String xh = SharedPreferencesUtil.getStringSp(login_daka.this, "stuNum", null);
        Log.e("xh", xh + "");
        if (StringUtil.isEmpty(xh, 9)) return;
        threadPool.execute(() -> {
            JSONObject id = schoolApi.getUserId(xh);
            if (id != null && Result.jsonResultIsTure(id) && id.containsKey("userid")) {
                String userid = id.getString("userid");
                EventBus.getDefault().post(new MessageEvent("login_daka", 5, userid));
            }
        });
    }

    @SuppressLint("HandlerLeak")
    public void getDKdata() {
        InputMethodManager manager = ((InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE));
        cx.setOnClickListener(view -> {
            if (manager != null)
                manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            if (sno.getText().toString().length() < 9) ToastUtil.showToast("请输入正确链接!");
            else {
                viewstub_loading.setVisibility(View.VISIBLE);
                stuNum = sno.getText().toString();
                if (stuNum.contains("=")) {
                    String str1 = stuNum.substring(0, stuNum.indexOf("="));
                    stuNum = stuNum.substring(str1.length() + 1);
                }
                threadPool.execute(() -> {
                    JSONObject jsonObject = schoolApi.getDk(stuNum);
                    if (jsonObject != null && jsonObject.containsKey("result") && jsonObject.getBooleanValue("result")) {
                        SharedPreferencesUtil.putStringSp(login_daka.this, "userid", stuNum);
                        EventBus.getDefault().post(new MessageEvent("login_daka", 4, jsonObject));
                    } else EventBus.getDefault().post(new MessageEvent("login_daka", 2, null));

                });

            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            super.onDestroy();
            this.finish();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("login_daka")) {
            switch (event.getWhat()) {
                case 1:
                    String[] idArry;
                    String re = event.getMessage();
                    if (re != null && re.length() != 0) {
                        idArry = re.trim().split(" ");
                        if (idArry.length >= 22) {
                            int sums = 0;
                            for (int i = 3; i < 14; i++) {
                                if (i == 3) {
                                    sums += Integer.parseInt(idArry[3]);
                                } else if (i < 13) {
                                    sums += Integer.parseInt(idArry[5 + 2 * (i - 4)]);
                                }
                            }
                            SharedPreferences sp;
                            SharedPreferences.Editor editor;
                            sp = PreferenceManager.getDefaultSharedPreferences(login_daka.this);
                            editor = sp.edit();
                            editor.putInt("daka", sums);
                            editor.apply();
                            List<dakaInfo> list = new ArrayList<>();
                            list.add(new dakaInfo("姓名", idArry[2].replace("姓名:", "")));
                            list.add(new dakaInfo("学号", idArry[1].replace("学号:", "")));
                            list.add(new dakaInfo("早操", idArry[3]));
                            list.add(new dakaInfo("体育俱乐部考勤", idArry[5]));
                            list.add(new dakaInfo("引体向上考勤", idArry[7]));
                            list.add(new dakaInfo("篮球比赛", idArry[9]));
                            list.add(new dakaInfo("田径", idArry[11]));
                            list.add(new dakaInfo("运动会单项", idArry[13]));
                            list.add(new dakaInfo("竞赛管理", idArry[15]));
                            list.add(new dakaInfo("考勤四", idArry[17]));
                            list.add(new dakaInfo("考勤五", idArry[19]));
                            list.add(new dakaInfo("增加次数", idArry[21]));
                            list.add(new dakaInfo("总次数", sums + ""));
                            twoTextViewAdapter adapter = new twoTextViewAdapter(list, this);
                            TextView title = findViewById(R.id.daka_title);
                            title.setVisibility(View.VISIBLE);
                            listView.setAdapter(adapter);

                        }
                    } else {
                        ToastUtil.showToast("没有查询到哦~请检查学号是否正确！");
                    }
                    viewstub_loading.setVisibility(View.GONE);
                    break;
                case 2:
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("无该学生信息!");
                    break;
                case 3:
                    viewstub_loading.setVisibility(View.GONE);
                    if (!select)
                        ToastUtil.showToast("数据请求超时!请连接校园网后重试！");
                    else ToastUtil.showToast("数据请求超时!");
                    break;
                case 4:
                    JSONObject jsonObject = (JSONObject) event.getObj();
                    Log.e("daka", jsonObject.toJSONString());
                    List<dakaInfo> list = new ArrayList<>();
                    list.add(new dakaInfo("姓名", jsonObject.getString("name")));
                    list.add(new dakaInfo("学号", jsonObject.getString("sno")));
                    for (int i = 0; i < 10; ++i) {
                        if (jsonObject.getJSONObject("subOption" + i) != null) {
                            list.add(new dakaInfo(jsonObject.getJSONObject("subOption" + i).getString("name"), "次数"));
                            list.add(new dakaInfo("正常次数", jsonObject.getJSONObject("subOption" + i).getString("normal")));
                            list.add(new dakaInfo("作弊次数", jsonObject.getJSONObject("subOption" + i).getString("cheat")));
                            list.add(new dakaInfo("违规次数", jsonObject.getJSONObject("subOption" + i).getString("violation")));
                            list.add(new dakaInfo("打卡时间", jsonObject.getJSONObject("subOption" + i).getString("time")));
                        } else break;
                    }
                    list.add(new dakaInfo("总次数", jsonObject.getString("total")));
                    twoTextViewAdapter adapter = new twoTextViewAdapter(list, this);
                    TextView title = findViewById(R.id.daka_title);
                    title.setVisibility(View.VISIBLE);
                    listView.setAdapter(adapter);
                    viewstub_loading.setVisibility(View.GONE);
                    break;
                case 5:
                    sno.setText(event.getMessage());
                    break;
                case 6:
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("未匹配到您的身份信息，请手动输入！");
                    break;

            }
        }
    }
}






